package me.itsoo.artemis.framework.repository.page;

import lombok.Data;
import lombok.EqualsAndHashCode;
import me.itsoo.artemis.framework.core.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * PageResult
 *
 * @param <T> T
 * @author zxy
 * @version 0.0.1
 * @since 2023/5/17
 */
@Data
@EqualsAndHashCode(callSuper = true)
public class PageResult<T> extends ArrayList<T> implements List<T> {

    private static final long serialVersionUID = -3355518351513893631L;

    private int pageNum = 1;

    private int pageSize = 10;

    private int pageCount;

    private long totalCount;

    private boolean hasNext = false;

    private List<T> data = Collections.emptyList();

    /**
     * 创建分页结果对象
     *
     * @param pageNum    int
     * @param pageSize   int
     * @param totalCount long
     * @param data       List
     * @param <T>        T
     * @return PageResult
     */
    public static <T> PageResult<T> create(int pageNum, int pageSize, long totalCount, List<T> data) {
        PageResult<T> result = new PageResult<>();
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setTotalCount(totalCount);
        result.setHasNext(totalCount > ((long) pageNum * pageSize));
        result.setData(data);
        return result;
    }

    /**
     * 设置结果集（同时设置 pageCount）
     *
     * @param data List
     */
    public void setData(List<T> data) {
        this.pageCount = data.size();
        this.data = data;
    }

    /**
     * 数据类型转换，避免 Mapper 上层编译报错
     *
     * @param list List
     * @param <T>  T
     * @return PageResult
     */
    public static <T> PageResult<T> init(List<T> list) {
        if (list instanceof PageResult) {
            return (PageResult<T>) list;
        }

        PageResult<T> result = new PageResult<>();
        result.setData(list);
        return result;
    }

    @Override
    public String toString() {
        return StringUtils.format("{\n" +
                "  pageNum: {}\n" +
                "  pageSize: {}\n" +
                "  pageCount: {}\n" +
                "  totalCount: {}\n" +
                "  hasNext: {}\n" +
                "  data: {}\n" +
                "}", pageNum, pageSize, pageCount, totalCount, hasNext, data);
    }
}
